import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login'

import { checktoken } from '../apis/users'



Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'login',
    component: Login
  },
  {
    path: '/index',
    name: 'index',
    // component: () => import('../views/Index.vue')
    component: () => import('../views/Index'),
    children: [{ path: '/index/main', name: 'index/main', component: () => import('../views/modules/Main') }, //主页-首页
    { path: '/index/orderman', name: 'index/orderman', component: () => import('../views/modules/Orderman') },  //主页-订单管理
    { path: '/index/itemlist', name: 'index/itemlist', component: () => import('../views/modules/itemmanager/ItemList') },  //主页-商品列表
    { path: '/index/itemadd', name: 'index/itemadd', component: () => import('../views/modules/itemmanager/ItemAdd') },  //主页-添加商品
    { path: '/index/itemtype', name: 'index/itemtype', component: () => import('../views/modules/itemmanager/ItemType') }, //主页-商品分类

    { path: '/index/storemanager', name: 'index/storemanager', component: () => import('../views/modules/Storemanager') }, //店铺管理

    { path: '/index/accountlist', name: 'index/accountlist', component: () => import('../views/modules/accountmanager/AccountList') },//主页-账号列表
    { path: '/index/accountAdd', name: 'index/accountAdd', component: () => import('../views/modules/accountmanager/AccountAdd') },//主页-添加账号
    { path: '/index/changepwd', name: 'index/changepwd', component: () => import('../views/modules/accountmanager/Changepwd') }, //修改密码
    { path: '/index/userinfo', name: 'index/userinfo', component: () => import('../views/modules/accountmanager/Userinfo') }, //管理员信息

    { path: '/index/itemstat', name: 'index/itemstat', component: () => import('../views/modules/sales/Itemstat') },  //主页-商品统计
    { path: '/index/orderstat', name: 'index/orderstat', component: () => import('../views/modules/sales/Orderstat') }]  //主页-订单统计
  },
  {
    path: '*',
    name: 404,
    component: () => import('../views/Error404')
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  //to: 即将前往的hash地址
  //from: 来自哪个hash地址
  //next: 下一步
  if (to.path == '/') {
    //在登陆就不拦截
    console.log(from);
    next()
  } else {
    // 判断破肯是否有效,失效就回到登录界面
    checktoken({ token: localStorage.token }).then(res => {
      // console.log(res);
      if (res.data.code == 0) {
        next()
      } else {
        next('/') //传到登录界面
      }
    })
  }

})


export default router
